from jenkins import Jenkins
from apps.extention.settings import config
from jinja2 import Template
import os
import uuid


class JenkinsClient:
    @classmethod
    def __server(cls):
        return Jenkins(config.JENKINS_URL, username=config.JENKINS_USER, password=config.JENKINS_PASSWORD)

    @classmethod
    def create_job(cls, git_url, ip, name, env, dingding):
        dir_name = os.path.join(os.path.abspath(os.path.dirname(__file__)))
        template_file = ''
        if env == 'pipeline':
            template_file = dir_name + '/jenkins_template/pipeline.xml'
        if env == 'test' or env == 'test3':
            template_file = dir_name + '/jenkins_template/test.xml'
        if env == 'ys':
            template_file = dir_name + '/jenkins_template/ys.xml'
        if template_file is None or template_file == '':
            raise Exception('没有匹配到环境，不能创建job')
        uid = uuid.uuid4()
        content = JobInfo(git_url, ip, name, env, uid, dingding)
        with open(template_file, 'r', ) as fp:
            tmpl = Template(fp.read())
            msg = tmpl.render(data=content)
            cls.__server().create_job('pipeline-{}'.format(name), msg)
            return {'job_uuid': uid}

    @classmethod
    def config_job(cls):
        pass


class JobInfo:
    def __init__(self, git_url, deploy_ip, name, env, uid, dingding):
        self.git_url = git_url
        self.deploy_ip = deploy_ip
        self.name = name
        self.env = env
        self.git_uuid = uid
        self.dingding = dingding
        self.exclusions = ''
